package com.wutianyi.service;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.SessionDAO;

import com.wutianyi.constants.Constants;
import com.wutianyi.module.member.dataobject.MemberDO;
import com.wutianyi.module.services.MemberServices;

public class SecurityManager {
	
	private SessionDAO sessionDao;
	private MemberServices memberServices;
	
	public Session doGetAuthenticationInfo(Serializable sessionId, AuthenticationToken token) {
		
		Session session = null;
		try {
			session = sessionDao.readSession(sessionId);
		} catch (Exception e) {

		}
		
		if (null == session && null != token) {
			UsernamePasswordToken upToken = (UsernamePasswordToken) token;
			MemberDO member = memberServices.getMemberByName(upToken.getUsername());
			String p = new Sha512Hash(upToken.getPassword()).toString();
			if (null != member && StringUtils.equals(p, member.getPassword())) {
				session = new SimpleSession();
				session.setAttribute(Constants.P_SESSION_M, member);
				sessionDao.create(session);
			}
		}
		return session;
	}
	
	public MemberDO getMember(HttpServletRequest request) {
		Session session = (Session) request.getAttribute(Constants.P_SESSION);
		if (null == session) {
			return null;
		}
		return (MemberDO) session.getAttribute(Constants.P_SESSION_M);
	}
	
	public SessionDAO getSessionDao() {
		return sessionDao;
	}
	
	public void setSessionDao(SessionDAO sessionDao) {
		this.sessionDao = sessionDao;
	}
	
	public MemberServices getMemberServices() {
		return memberServices;
	}
	
	public void setMemberServices(MemberServices memberServices) {
		this.memberServices = memberServices;
	}
	
}
